<template>
  <div id="app">
    <div>
      <span>姓名:</span>
      <input type="text" v-model.trim="user.name"/>
    </div>
    <div>
      <span>年龄:</span>
      <input type="number" v-model.number="user.age"/>
    </div>
    <div>
      <span>性别:</span>
      <select v-model="user.sex">
        <option value="男">男</option>
        <option value="女">女</option>
      </select>
    </div>
    <div>
      <button @click="addBtn">添加/修改</button>
    </div>
    <div>
      <table
        border="1"
        cellpadding="10"
        cellspacing="0"
        v-show="arr.length > 0"
      >
        <tr>
          <th>序号</th>
          <th>姓名</th>
          <th>年龄</th>
          <th>性别</th>
          <th>操作</th>
        </tr>
        <tr v-for="(item, index) in arr" :key="index">
          <td>{{ index + 1 }}</td>
          <td>{{ item.name }}</td>
          <td>{{ item.age }}</td>
          <td>{{ item.sex }}</td>
          <td>
            <button @click="delFn(index)">删除</button>
            <button @click="edtFn(item,index)">编辑</button>
          </td>
        </tr>
      </table>
    </div>
  </div>
</template>
 
<script>
export default {
  data() {
    return {
      user: {
        //绑定对象
        name: "",
        age: 0,
        sex: "",
      },
      editIndex: -1,
      arr: [
        {
          name: "小芳",
          age: 19,
          sex: "女",
        },
        {
          name: "小花",
          age: 18,
          sex: "女",
        },
      ],
    }
  },
  methods: {
    addBtn() {
      // 添加/修改方法
      if (
        this.user.name.length === 0 ||
        this.user.age === 0 ||
        this.user.sex.length === 0
      ) {
        alert("干啥呢，输错啦，重新输入吧！")
        return
      }
 
      if (this.editIndex === -1) {
        // 新增
        this.arr.push({ ...this.user })
      } else {
        // 编辑
        this.$set(this.arr, this.editIndex, { ...this.user }) // 修改数组里某个值导致v-for更新
      }
      // 清空输入框
      this.user.name = ""
      this.user.age = 0
      this.user.sex = ""
    },
    edtFn(theitem, index) {
      // 编辑-点击事件
      this.user = { ...theitem }
      this.editIndex = index
    },
    delFn(index) {
      // 删除方法
      this.arr.splice(index, 1)
    },
  },
}
</script>
